package cn.lagou.dw.flume.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.Charsets;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.SinkRunner;
import org.apache.flume.interceptor.Interceptor;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Alex Zhang
 */
public class LogTimestampInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(SinkRunner.class);

    public static class Builder implements Interceptor.Builder {
        @Override
        public Interceptor build() {
            return new LogTimestampInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

    /**
     * 初始化
     */
    @Override
    public void initialize() {

    }

    /**
     * 逐条处理event
     *
     * @param event event
     * @return 处理好的event
     */
    @Override
    public Event intercept(Event event) {
        final String logTypeStart = "start";
        final String logTypeEvent = "event";
        String eventBody = new String(event.getBody(), Charsets.UTF_8);
        Map<String, String> eventHeaders = event.getHeaders();
        String[] eventBodyFieldArray = eventBody.split("\\s+");
        try {
            String jsonString = eventBodyFieldArray[6];
            JSONObject jsonObject = JSON.parseObject(jsonString);
            String tsString = null;
            String logType = eventHeaders.getOrDefault("logtype", "");
            logger.info(logType);
            // start log
            if (logTypeStart.equals(logType)) {
                tsString = jsonObject.getJSONObject("app_active").getString("time");
            }
            // event log
            if (logTypeEvent.equals(logType)) {
                JSONArray eventArray = jsonObject.getJSONArray("lagou_event");
                if (eventArray.size() > 0) {
                    tsString = eventArray.getJSONObject(0).getString("time");
                }
            }
            if (null != tsString) {
                long timestamp = Long.parseLong(tsString);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                Instant instant = Instant.ofEpochMilli(timestamp);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                String date = formatter.format(localDateTime);
                eventHeaders.put("logtime", date);
                event.setHeaders(eventHeaders);
            } else {
                eventHeaders.put("logtime", "unknown");
                event.setHeaders(eventHeaders);
            }
        } catch (Exception e) {
            eventHeaders.put("logtime", "unknown");
            event.setHeaders(eventHeaders);
        }
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        List<Event> events = new ArrayList<>();
        for (Event event : list) {
            Event processed = intercept(event);
            if (null != processed) {
                events.add(processed);
            }
        }
        return events;
    }

    @Override
    public void close() {

    }
}
